//
//  QRCodeViewController.swift
//  SwiftWB
//
//  Created by 钟清 on 17/3/28.
//  Copyright © 2017年 Zhong Qing. All rights reserved.
//

import UIKit
import AVFoundation

class QRCodeViewController: UIViewController {

    @IBOutlet weak var customContainerView: UIView!
    @IBOutlet weak var scanLinesView: UIView!
    @IBOutlet weak var customTabBar: UITabBar!
    @IBOutlet weak var scanLinesCons: NSLayoutConstraint!
    @IBOutlet weak var containerHeightCons: NSLayoutConstraint!
    @IBOutlet weak var customLabel: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        /// 默认选中
        customTabBar.selectedItem = customTabBar.items![0]
        /// 监听底部工具条点击
        customTabBar.delegate = self
        /// 开始扫描二维码
        scanQRCode()
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(true)
        startAnimation()
    }
    
    // MARK: - 内部控制方法
    private func scanQRCode() {
        if !session.canAddInput(input) {
            return
        }
        if !session.canAddOutput(output) {
            return
        }
        session.addInput(input)
        session.addOutput(output)
        /// 需设置可解析的输出类型
        output.metadataObjectTypes = output.availableMetadataObjectTypes
        /// 监听解析数据
        output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
        /// 预览层
        view.layer.insertSublayer(previewLayer, atIndex: 0)
        previewLayer.frame = view.frame
        /// 添加描框图层
        view.layer.addSublayer(containerLayer)
        containerLayer.frame = view.bounds
        /// 开始扫描
        session.startRunning()
    }
    private func startAnimation() {
        scanLinesCons.constant = -containerHeightCons.constant
        view.layoutIfNeeded()
        UIView.animateWithDuration(1.0) {
            UIView.setAnimationRepeatCount(MAXFLOAT)
            self.scanLinesCons.constant = self.containerHeightCons.constant
            self.view.layoutIfNeeded()
        }
    }
    
    
    // MARK: - Lazy
    private lazy var input: AVCaptureDeviceInput? = {
       let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        return try? AVCaptureDeviceInput(device: device)
    }()
    private lazy var session: AVCaptureSession = AVCaptureSession()
    private lazy var output: AVCaptureMetadataOutput = { // 设置扫描区域
        let out = AVCaptureMetadataOutput()
        let viewRect = self.view.frame
        let containerRect = self.customContainerView.frame
        /// 系统默认以横屏左上角为原点：out.rectOfInterest = CGRect(x: 0, y: 0, width: 1, height: 1)
        let xScale = containerRect.origin.x / viewRect.height
        let yScale = containerRect.origin.y / viewRect.width
        let widthScale = containerRect.width / viewRect.height
        let heightScale = containerRect.height / viewRect.width
        out.rectOfInterest = CGRect(x: xScale, y: yScale, width: widthScale, height: heightScale)
        return out
    }()
    
    private lazy var previewLayer: AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.session)
    /// 保存描框的图层
    private lazy var containerLayer: CALayer = CALayer()
    
    // MARK: - Event
    @IBAction func closeButtonClick(sender: AnyObject) {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @IBAction func photoButtonClick(sender: AnyObject) {
        
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
            return
        }
        let imagePickerVC = UIImagePickerController()
        imagePickerVC.delegate = self
        presentViewController(imagePickerVC, animated: true, completion: nil)
    }

}

// MARK: - Delegate
extension QRCodeViewController : UITabBarDelegate {
    func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
        containerHeightCons.constant = (item.tag == 1 ? 120 : 240)
        view.layoutIfNeeded()
        scanLinesView.layer.removeAllAnimations()
        startAnimation()
    }
}

extension QRCodeViewController : AVCaptureMetadataOutputObjectsDelegate {
    func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
        /// 获取文本框预览文字
        customLabel.text = metadataObjects.last?.stringValue
        
        clearLayers()
        
        /// 通过预览涂层将系统的corners数据转为可识别数据
        guard let metadata = metadataObjects.last as? AVMetadataObject else {
            return
        }
        let objc = previewLayer.transformedMetadataObjectForMetadataObject(metadata)
        
        /// 描框
        drawLines(objc as! AVMetadataMachineReadableCodeObject)
    
    }
    
    private func drawLines(objc: AVMetadataMachineReadableCodeObject) {
        /// 1,校验
        guard let array = objc.corners else {
            ZQLog("corners数据转换失败")
            return
        }
        /// 2,设置
        let layer = CAShapeLayer()
        layer.lineWidth = 2
        layer.strokeColor = UIColor.redColor().CGColor
        layer.fillColor = UIColor.clearColor().CGColor
        /// 3,第一点
        let path = UIBezierPath()
        var point = CGPointZero
        var index = 0
        CGPointMakeWithDictionaryRepresentation((array[0] as! CFDictionary), &point)
        path.moveToPoint(point)
        /// 4,拼接线段
        while index < array.count {
            index += 1
            CGPointMakeWithDictionaryRepresentation((array[index] as! CFDictionary), &point)
            path.addLineToPoint(point)
        }
        /// 5,关闭路径
        path.closePath()
        layer.path = path.CGPath
        /// 6，添加
        containerLayer.addSublayer(layer)
    }
    
    ///  清空描边
    private func clearLayers() {
        guard let sublayers = containerLayer.sublayers else {
        return
        }
        for layer in sublayers {
        layer.removeFromSuperlayer()
        }
    
    }
}

extension QRCodeViewController : UINavigationControllerDelegate, UIImagePickerControllerDelegate {
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        guard let image = info["UIImagePickerControllerOriginalImage"] as? UIImage else {
            ZQLog("从相册获得UIImage")
            return
        }
        guard let ciImage = CIImage(image: image) else {
            ZQLog("转成CIImage")
            return
        }
        let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy : CIDetectorAccuracyLow])
        let results = detector.featuresInImage(ciImage)
        for result in results {
            ZQLog((result as! CIQRCodeFeature).messageString)
        }
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}